<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, user-scalable=no"
    />
    <title>选择位置</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      body {
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
          sans-serif;
        height: 100vh;
        overflow: hidden;
      }

      #map {
        height: calc(100vh - 120px);
        width: 100%;
      }

      .header {
        height: 60px;
        background: #fff;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 15px;
        border-bottom: 1px solid #eee;
        position: relative;
        z-index: 1000;
      }

      .header .title {
        font-size: 18px;
        font-weight: 500;
        color: #333;
      }

      .header .close-btn {
        background: none;
        border: none;
        font-size: 16px;
        color: #666;
        cursor: pointer;
        padding: 5px;
      }

      .footer {
        height: 60px;
        background: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        border-top: 1px solid #eee;
        position: relative;
        z-index: 1000;
      }

      .button-group {
        display: flex;
        gap: 10px;
        margin-top: 10px;
      }

      .clear-btn {
        background: #666;
        color: white;
        border: none;
        border-radius: 6px;
        padding: 12px 20px;
        font-size: 16px;
        cursor: pointer;
        flex: 1;
      }

      .clear-btn:hover {
        background: #555;
      }

      .confirm-btn {
        background: #007aff;
        color: white;
        border: none;
        border-radius: 6px;
        padding: 12px 30px;
        font-size: 16px;
        cursor: pointer;
        min-width: 120px;
      }

      .confirm-btn:hover {
        background: #0056cc;
      }

      .confirm-btn:disabled {
        background: #ccc;
        cursor: not-allowed;
      }

      .address-info {
        position: absolute;
        top: 80px;
        left: 15px;
        right: 15px;
        background: rgba(255, 255, 255, 0.95);
        padding: 10px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        z-index: 1000;
        max-height: 80px;
        overflow: hidden;
      }

      .address-text {
        font-size: 14px;
        color: #333;
        line-height: 1.4;
      }

      .loading {
        text-align: center;
        color: #666;
        font-size: 14px;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>

    <div class="address-info">
      <div id="address" class="address-text loading">正在获取位置信息...</div>
    </div>

    <div class="footer">
      <div class="button-group">
        <button class="clear-btn" id="clearBtn" onclick="clearSelection()">
          清空
        </button>
        <button
          class="confirm-btn"
          id="confirmBtn"
          onclick="confirmSelection()"
          disabled
        >
          确认选择
        </button>
      </div>
    </div>

    <script>
      let map;
      let marker;
      let geocoder;
      let selectedLocation = null;
      let selectedAddress = "";

      // 从URL参数获取API密钥
      function getApiKey() {
        const urlParams = new URLSearchParams(window.location.search);
        const apiKey =
          urlParams.get("apiKey") || "AIzaSyDNeFm8A-c5Nv0hDxlYAK0hnf2L_O3tw2I";

        // 基本的API密钥格式验证
        if (
          !apiKey ||
          apiKey === "YOUR_GOOGLE_MAPS_API_KEY" ||
          apiKey.length < 30
        ) {
          console.warn("API密钥可能无效:", apiKey);
          handleMapError("API密钥无效或未配置");
          return null;
        }

        return apiKey;
      }

      function initMap() {
        try {
          console.log("开始初始化 Google Maps...");

          // 检查 Google Maps API 是否可用
          if (typeof google === "undefined" || !google.maps) {
            throw new Error("Google Maps API 未正确加载");
          }

          // 默认位置（北京）
          const defaultLocation = { lat: 39.9042, lng: 116.4074 };

          const mapElement = document.getElementById("map");
          if (!mapElement) {
            throw new Error("地图容器元素未找到");
          }

          map = new google.maps.Map(mapElement, {
            zoom: 15,
            center: defaultLocation,
            mapTypeControl: false,
            streetViewControl: false,
            fullscreenControl: false,
            gestureHandling: "greedy",
          });

          geocoder = new google.maps.Geocoder();

          // 创建标记
          marker = new google.maps.Marker({
            position: defaultLocation,
            map: map,
            draggable: true,
            title: "拖动选择位置",
          });

          // 监听地图点击事件
          map.addListener("click", function (event) {
            updateMarkerPosition(event.latLng);
          });

          // 监听标记拖拽事件
          marker.addListener("dragend", function (event) {
            updateMarkerPosition(event.latLng);
          });

          console.log("Google Maps 初始化成功");

          // 尝试获取用户当前位置
          if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
              function (position) {
                console.log("获取到用户位置:", position.coords);
                const userLocation = {
                  lat: position.coords.latitude,
                  lng: position.coords.longitude,
                };
                map.setCenter(userLocation);
                updateMarkerPosition(
                  new google.maps.LatLng(userLocation.lat, userLocation.lng)
                );
              },
              function (error) {
                console.warn("获取位置失败:", error.message);
                // 获取位置失败，使用默认位置
                updateMarkerPosition(
                  new google.maps.LatLng(
                    defaultLocation.lat,
                    defaultLocation.lng
                  )
                );
              },
              {
                timeout: 10000,
                enableHighAccuracy: true,
                maximumAge: 300000,
              }
            );
          } else {
            console.log("浏览器不支持地理定位，使用默认位置");
            updateMarkerPosition(
              new google.maps.LatLng(defaultLocation.lat, defaultLocation.lng)
            );
          }
        } catch (error) {
          console.error("初始化地图时发生错误:", error);
          handleMapError(error.message);
        }
      }

      function updateMarkerPosition(latLng) {
        marker.setPosition(latLng);
        selectedLocation = {
          latitude: latLng.lat(),
          longitude: latLng.lng(),
        };

        // 反向地理编码获取地址
        geocoder.geocode({ location: latLng }, function (results, status) {
          const addressDiv = document.getElementById("address");
          const confirmBtn = document.getElementById("confirmBtn");

          if (status === "OK" && results[0]) {
            selectedAddress = results[0].formatted_address;
            addressDiv.textContent = selectedAddress;
            confirmBtn.disabled = false;
          } else {
            addressDiv.textContent = "无法获取地址信息";
            confirmBtn.disabled = true;
          }
        });
      }

      function confirmLocation() {
        if (selectedLocation && selectedAddress) {
          const result = {
            latitude: selectedLocation.latitude,
            longitude: selectedLocation.longitude,
            address: selectedAddress,
            name: selectedAddress,
          };

          // 通知父页面
          if (window.parent) {
            window.parent.postMessage(
              {
                type: "locationSelected",
                data: result,
              },
              "*"
            );
          }
        }
      }

      function clearSelection() {
        selectedLocation = null;
        selectedAddress = "";

        const addressDiv = document.getElementById("address");
        const confirmBtn = document.getElementById("confirmBtn");

        addressDiv.textContent = "请在地图上选择位置";
        addressDiv.className = "address-text";
        confirmBtn.disabled = true;

        // 重置地图到默认位置
        const defaultLocation = { lat: 39.9042, lng: 116.4074 };
        map.setCenter(defaultLocation);
        marker.setPosition(defaultLocation);
      }

      function closeMap() {
        if (window.parent) {
          window.parent.postMessage(
            {
              type: "mapClosed",
            },
            "*"
          );
        }
      }

      // 错误处理函数
      function handleMapError(error) {
        console.error("Google Maps 加载错误:", error);
        const addressDiv = document.getElementById("address");
        addressDiv.innerHTML = `
                <div style="color: #ff4444; text-align: center;">
                    <div>地图加载失败</div>
                    <div style="font-size: 12px; margin-top: 5px;">请检查网络连接或API密钥</div>
                    <button onclick="retryLoadMap()" style="margin-top: 10px; padding: 5px 10px; background: #007AFF; color: white; border: none; border-radius: 4px;">重试</button>
                </div>
            `;
      }

      // 重试加载地图
      function retryLoadMap() {
        const addressDiv = document.getElementById("address");
        addressDiv.innerHTML = '<div class="loading">正在重新加载地图...</div>';
        loadGoogleMaps();
      }

      // 全局错误处理
      window.gm_authFailure = function () {
        handleMapError("API密钥验证失败");
      };

      // 动态加载谷歌地图API
      function loadGoogleMaps() {
        const apiKey = getApiKey();

        // 如果API密钥验证失败，直接返回
        if (!apiKey) {
          return;
        }

        console.log(
          "正在加载 Google Maps API，密钥:",
          apiKey.substring(0, 10) + "..."
        );

        // 移除之前的脚本（如果存在）
        const existingScript = document.querySelector(
          'script[src*="maps.googleapis.com"]'
        );
        if (existingScript) {
          existingScript.remove();
        }

        const script = document.createElement("script");
        script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&callback=initMap&libraries=geometry`;
        script.async = true;
        script.defer = true;

        // 添加错误处理
        script.onerror = function () {
          handleMapError("无法加载 Google Maps API 脚本");
        };

        document.head.appendChild(script);
      }

      // 页面加载完成后初始化
      window.addEventListener("load", function () {
        // 检查网络连接
        if (!navigator.onLine) {
          handleMapError("网络连接不可用");
          return;
        }
        loadGoogleMaps();
      });
    </script>
  </body>
</html>
